<template>
  <el-container>
    <el-header style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;">
      <div>
        <svg-icon class="primary" :icon-class="$route.meta.icon" />
        <span class="primary">{{ $route.meta.title }}</span>
      </div>
      <div class="header-button-container">
        <el-button icon="el-icon-plus" type="primary" @click="addShowDialog" v-permission="['emptyBarrel.add']">新增</el-button>
      </div>
    </el-header>
    <div class="pd10">
      <el-table v-loadMore="[payLoads,'empty-barrel']" :data="emptyBarrelList" border stripe :height="curHeight" style="width: 100%">
        <el-table-column label="缩略图" align="center" width="80">
          <template slot-scope="scope">
            <img style="width: 50px; height: 50px; vertical-align:middle; overflow: hidden;" :src="scope.row.productThumbnail" alt="">
          </template>
        </el-table-column>
        <el-table-column label="编码" width="150" align="left" prop="sn" />
        <el-table-column label="空桶名称" align="left" prop="productName" />
        <el-table-column label="" align="left" prop="productPrice" />
        <<el-table-column label="单位" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center" prop="isMarketable">
          <template slot-scope="scope">
            <el-tag type="success">
              <span>{{ scope.row.isMarketable | watchType }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <<el-table-column label="排序" align="center" width="70" prop="orders" :render-header="ordersIcons">
          <template slot-scope="scope">
            <el-input v-model="scope.row.orders" @blur="bulrOrders(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="功能" align="center" fixed="right" width="80">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="releaseEmptyBarrel(scope.row)" v-permission="['emptyBarrel.up','emptyBarrel.down']">
              {{ scope.row.isMarketable ?'下架':'上架' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="80">
          <template slot-scope="scope">
            <div>
              <el-tooltip class="item" effect="dark" content="编辑" placement="top-start" v-permission="['emptyBarrel.edit']">
                <a @click="editShowDialog(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit" />
                </a>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start" v-permission="['emptyBarrel.del']">
                <a style="margin-left: 10px" @click="deleteEmptyBarrel(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete" />
                </a>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadEmptyBarrel" />
    </el-footer>

    <!-- 添加窗口 -->
    <el-dialog v-if="addHackReset" width="900px" title="空桶押金" :visible.sync="addFormVisible" @close="addClose">
      <el-form ref="addFormRef" style="margin: 30px 0;" :model="addForm" :rules="productRules" label-width="110px">
        <el-row>
          <el-col :span="18">
            <el-form-item prop="productId" label="选择押金商品">
              <search-options ref="addProductRef" :tips-text="'请选择商品名称'" :options-style="'width: 80%'" :request="'product'" :fixed-params="productParams" @getValue="addQueryProduct" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="position: relative" label="选择商品">
          <span class="el-icon-plus add-add-click" style="position: absolute; left: -25px; top: 25px; color: #409EFF;" @click="addDataItem" />
          <el-table :data="addForm.itemList" stripe border class="add-form-css" style="width: 100%">
            <el-table-column label="桶装水">
              <template slot-scope="scope">
                <el-form-item style="margin-bottom: 0;" :prop="`itemList[${scope.$index}].productName`" :rules="productRules.productName">
                  <el-select
                    v-model="addForm.itemList[scope.$index].productId"
                    style="width: 100%;"
                    placeholder="请选择对应商品名称"
                    filterable
                    :filter-method="queryProduct"
                    @change="addFromAddItemList(scope.$index, scope.row.productId)"
                  >
                    <el-option v-for="item in productIdOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item></template>
            </el-table-column>
            <el-table-column label="缩略图" width="80">
              <template slot-scope="scope">
                <img :key="Math.random()" style="width: 50px; height: 50px; vertical-align:middle; overflow: hidden;" :src="scope.row.productThumbnail" alt="">
              </template>
            </el-table-column>
            <el-table-column label="价格" width="110" prop="productPrice" />
            <el-table-column label="单位" width="80" prop="unit" />
            <el-table-column label="操作" width="80" align="center" fixed="right">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                  <a v-show="addForm.itemList.length > 1" @click="addFromDelItemList(scope.$index)">
                    <i style="color: #F56C6C" class="el-icon-delete" />
                  </a>
                </el-tooltip>
              </template>
            </el-table-column>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClick">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改窗口 -->
    <el-dialog v-if="editHackReset" width="900px" title="选择桶装水" :visible.sync="editFormVisible" @close="editClose">
      <el-form ref="editFormRef" style="margin: 30px 0;" :model="editForm" :rules="productRules" label-width="110px">
        <el-row>
          <el-col :span="14">
            <el-form-item prop="productId" label="选择押金商品">
              <search-options v-if="editHackReset" ref="editProductRef" :tips-text="'请选择商品名称'" :options-style="'width: 100%'" :request="'product'" disabled :clearable="false" :find-value="[{name: editForm.productName, id: editForm.productId}]" :fixed-params="productParams" @getAllData="editQueryProduct" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item style="position: relative;" label="选择商品">
          <span class="el-icon-plus edit-add-click" style="position: absolute; left: -25px; top: 25px; color: #409EFF;" @click="editDataItem" />
          <el-table :data="editForm.itemList" class="edit-form-css" stripe border style="width: 100%">
            <el-table-column prop="productName" label="商品">
              <template slot-scope="scope">
                <el-form-item style="margin-bottom: 0;" :prop="`itemList[${scope.$index}].productName`" :rules="productRules.productName">
                  <el-select
                    v-model="editForm.itemList[scope.$index].productId"
                    style="width: 100%;"
                    placeholder="请选择对应商品名称"
                    filterable
                    :filter-method="queryProduct"
                    @change="editFromAddItemList(scope.$index, scope.row.productId)"
                  >
                    <el-option v-for="item in productIdOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item></template>
            </el-table-column>
            <el-table-column label="缩略图" width="80">
              <template slot-scope="scope">
                <img :key="Math.random()" style="width: 50px; height: 50px; vertical-align:middle; overflow: hidden;" :src="scope.row.productThumbnail" alt="">
              </template>
            </el-table-column>
            <el-table-column label="价格" width="110" prop="productPrice" />
            <el-table-column label="单位" width="80" prop="unit" />
            <el-table-column label="操作" width="80" align="center" fixed="right">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                  <a v-show="editForm.itemList.length > 1" @click="editFromDelItemList(scope.$index)">
                    <i style="color: #F56C6C" class="el-icon-delete" />
                  </a>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editClick">确 定</el-button>
      </div>
    </el-dialog>

  </el-container>
</template>

<script>
import loadMore from '@/utils/loadMore.js'
import permission from '@/directive/permission/index.js' // 权限判断指令
import { list, save, find, update, del } from '@/api/emptyBarrel'
import { list as productList, updateProduct } from '@/api/product'
import Pagination from '@/components/Pagination'
import searchOptions from '@/components/searchOptions'
import utils from '../../utils/utils.js'

export default {
  name: 'EmptyBarrel',
  directives: { permission, loadMore },
  components: { Pagination, searchOptions },
  filters: {
    watchType(val) {
      if (val === false) {
        return '未上架'
      } else if (val === true) {
        return '已上架'
      }
    }
  },
  data() {
    return {
      queryType: true,
      pageNum: 1,
      pageSize: 20,
      total: 0,
      curHeight: null,
      payLoads: '',
      productMark: false, // 防抖
      productIdOptions: [],
      emptyBarrelList: [],
      productParams: {
        'subType': 0,
        'type': 1,
        'isList': true
      },
      addFormVisible: false,
      addHackReset: false,
      addForm: {},
      editFormVisible: false,
      editHackReset: false,
      editForm: {},
      productRules: {
        productId: [
          { required: true, message: '请选择商品名称', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请选择商品名称', trigger: 'blur' }
        ],
        productPrice: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        convRate: [
          { required: true, message: '请输入捆绑系数', trigger: 'blur' }
        ]
      }
    }
  },
  activated() {
    this.payLoads = new Date().getTime()
  },
  created() {
    this.loadEmptyBarrel()
  },
  mounted() {
    this.comeIn()
    this.beforeMount()
  },
  methods: {
    beforeMount() {
      var _this = this
      window.onresize = () => {
        return (() => {
          var h = document.documentElement.clientHeight || document.body.clientHeight
          if (this.queryType === false) {
            _this.curHeight = h - 266// 减去页面上固定高度height
          } else {
            _this.curHeight = h - 220// 减去页面上固定高度height
          }
        })()
      }
    },
    comeIn() {
      console.log('222')
      var h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 220// 减去页面上固定高度height
    },
    loadEmptyBarrel() {
      const params = new URLSearchParams()
      params.append('pageNum', this.pageNum)
      params.append('pageSize', this.pageSize)
      params.append('type', 3)
      list(params).then(res => {
        console.log(res)
        this.emptyBarrelList = res.data.data
        this.total = res.data.total
      }).catch(() => {})
    },
    queryProduct(query) {
      clearTimeout(this.productMark)
      this.productMark = setTimeout(() => {
        this.productIdOptions = []
        productList({ name: query, isList: true, type: 0 }).then(res => {
          this.productIdOptions = res.data.data
          if (utils.isNull(this.editForm.itemList)) { return }
          this.editForm.itemList.forEach((item, index) => {
            const notFound = this.productIdOptions.find(val => { return val.id == item.productId }) // 找到列表里没有的数据
            if (!notFound && item.productId !== '') {
              const obj = {
                name: item.productName,
                id: item.productId,
                thumbnail: item.productThumbnail,
                price: item.productPrice,
                unit: item.unit
              }
              this.productIdOptions.unshift(obj) // 把没有的数据添加到列表里
            }
          })
        }).catch(err => {
          console.log(err)
        })
      }, 300)
    },
    addQueryProduct(value) { // 添加的查询商品
      this.addForm.productId = value
    },
    addShowDialog() {
      this.queryProduct()
      this.addForm = {
        productId: '',
        itemList: [
          {
            productId: '',
            productName: '',
            productPrice: '',
            convRate: 1
          }
        ],
        type: 3,
        quantity: 1
      }
      this.$nextTick(() => { // 避免数据更新页面未刷新
        this.addHackReset = true
      })
      setTimeout(() => { this.$refs.addProductRef.resetValue() }, 200)
      this.addFormVisible = true
      this.setAddClickHeight(0)
    },
    addFromAddItemList(index, productId) {
      // 给对应itemList赋值对应属性
      const OptionsIndex = this.productIdOptions.find(val => { return val.id == productId })
      this.addForm.itemList[index].productName = OptionsIndex.name
      this.addForm.itemList[index].productPrice = OptionsIndex.price
      this.addForm.itemList[index].productThumbnail = OptionsIndex.thumbnail
      this.addForm.itemList[index].unit = OptionsIndex.unit
    },
    addDataItem() {
      const obj = {
        productId: '',
        productName: '',
        productPrice: '',
        convRate: 1
      }
      this.addForm.itemList.push(obj)
      this.setAddClickHeight(0)
    },
    addClick() { // 新增
      this.$refs['addFormRef'].validate((valid) => {
        if (valid) {
          const params = this.addForm
          params.itemList.forEach((item, index) => {
            delete params.itemList[index].unit
          })
          params.type = 3
          save(params).then(res => {
            console.log(res)
            this.loadEmptyBarrel()
            this.addFormVisible = false
          }).catch(() => {})
        } else {
          return false
        }
      })
    },
    addFromDelItemList(index) { // 删除itemList单项
      this.addForm.itemList.splice(index, 1)
      this.setAddClickHeight(0)
    },
    addClose() {
      this.addHackReset = true
    },
    editShowDialog(row) { // 编辑
      find(row.id).then(res => {
        this.editForm = res.data.bom
        this.$nextTick(() => { // 避免数据更新页面未刷新
          this.editHackReset = true
        })
        this.setAddClickHeight(1)
        this.$refs.editProductRef.queryOptions() // 避免数据更新页面未刷新
      }).catch(() => {})
      this.editFormVisible = true
    },
    editQueryProduct(value) { // 添加的查询商品
      this.editForm.productId = value.id
      this.editForm.productName = value.name
      this.queryProduct()
    },
    editDataItem() {
      const obj = {
        productId: '',
        productName: '',
        productPrice: '',
        convRate: 1
      }
      this.editForm.itemList.push(obj)
      this.setAddClickHeight(1)
    },
    editFromAddItemList(index, productId) {
      // 给对应itemList赋值对应属性
      const OptionsIndex = this.productIdOptions.find(val => { return val.id == productId })
      this.editForm.itemList[index].productName = OptionsIndex.name
      this.editForm.itemList[index].productPrice = OptionsIndex.price
      this.editForm.itemList[index].productThumbnail = OptionsIndex.thumbnail
      this.editForm.itemList[index].unit = OptionsIndex.unit
      this.setAddClickHeight(1)
    },
    editClick() { // 修改
      this.$refs['editFormRef'].validate((valid) => {
        if (valid) {
          const params = {
            id: this.editForm.id,
            productId: this.editForm.productId,
            type: 3,
            quantity: 1
          }
          const itemList = this.editForm.itemList
          itemList.forEach(item => {
            delete item.unit
            delete item.sn
          })
          params.itemList = itemList
          update(params).then(res => {
            console.log(res)
            this.loadEmptyBarrel()
            this.editFormVisible = false
          }).catch(() => {})
        } else {
          return false
        }
      })
    },
    editFromDelItemList(index) { // 删除itemList单项
      this.editForm.itemList.splice(index, 1)
      this.setAddClickHeight(1)
    },
    editClose() {
      this.editHackReset = false
      this.editForm.itemList = []
    },

    releaseEmptyBarrel(row) { // 上架
      this.$confirm(row.isMarketable ? '确认下架?' : '确认上架?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateProduct({
          id: row.productId,
          isMarketable: !row.isMarketable
        }).then(res => {
          console.log(res)
          for (let i = 0; i < this.emptyBarrelList.length; i++) {
            if (this.emptyBarrelList[i].productId == res.data.id) {
              this.emptyBarrelList[i].isMarketable = res.data.isMarketable
            }
          }
          this.$message({ type: 'success', message: row.isMarketable ? '下架成功' : '上架成功' })
        }).catch(() => {})
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消上架' })
      })
    },
    deleteEmptyBarrel(data) {
      console.log(data)
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(data.id).then(res => {
          console.log(res)
          this.emptyBarrelList.forEach((item, index) => {
            if (item.id === data.id) {
              this.emptyBarrelList.splice(index, 1)
            }
          })
          this.$message({
            message: res.content,
            offset: 120,
            center: true
          })
        }).catch(() => {})
      }).catch(() => {})
    },
    ordersIcons(h, { column }) { // 排序
      const inReview = '点击下方数字区域可直接更改排序。'
      return h('div', [
        h('span', column.label),
        h(
          'el-tooltip',
          {
            props: {
              placement: 'top'
            }
          },
          [
            h(
              'div',
              {
                slot: 'content',
                style: {
                  width: '200px',
                  whiteSpace: 'normal',
                  'margin-bottom': '10px'
                }
              },
              inReview
            ),
            h('i', {
              class: 'el-icon-question',
              style: 'color:#888888;margin-left:5px;position:absolute'
            })
          ]
        )
      ])
    },
    bulrOrders(data) {
      console.log(data)
      updateProduct({
        id: data.productId,
        orders: data.product.orders,
        isMarketable: data.isMarketable
      }).then(res => {
        console.log(res)
      }).catch(() => {})
    },
    setAddClickHeight(data) {
      let itemList
      let mask
      let click
      if (data == 0) { // 判断要获取哪个列表的数据
        itemList = this.addForm.itemList
        mask = '.add-form-css'
        click = '.add-add-click'
      } else {
        itemList = this.editForm.itemList
        mask = '.edit-form-css'
        click = '.edit-add-click'
      }
      setTimeout(() => {
        // 获取表头的高度
        const tableTopHeight = document.querySelector(`${mask} .el-table__header`).offsetHeight
        const tableItem = document.querySelector(mask)
        let itemClass // 判断列表是否有数据
        if (tableItem.className.indexOf('el-table--enable-row-transition') > -1) {
          itemClass = '.el-table__row' // 有数据
        } else {
          itemClass = '.el-table__empty-text' // 没数据
        }
        // 获取一行表格高度
        const tableHeight = document.querySelector(`${mask} ${itemClass}`).offsetHeight
        // 获取添加按钮样式
        const addClickStyle = document.querySelector(`${click}`)
        // 获取添加按钮高度
        const addClickHeight = addClickStyle.offsetHeight
        // 设置添加按钮的位置
        const moveHeight = tableTopHeight + ((itemList.length > 0 ? itemList.length - 1 : 0) * tableHeight) + ((tableHeight - addClickHeight) / 2)
        /* console.log(tableTopHeight, 'tableTopHeight')
        console.log(tableHeight, 'tableHeight')
        console.log(moveHeight, 'moveHeight') */
        addClickStyle.style.top = moveHeight + 'px'
      }, 100)
    }
  }
}
</script>
<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #eeeeee;
  }

  /deep/ .el-dialog__header {
    border: 1px solid #eeeeee !important;
    padding: 15px !important;
  }

  /deep/ .el-dialog__body {
    padding: 0px 20px !important;
  }

  .popup_content {
    padding-bottom: 0px !important;
  }
</style>
